package com.cn.qgx428.orderingmeal.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.LinearLayout;


import com.cn.qgx428.orderingmeal.viewHolder.RViewHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by QinX on 2017/5/8.
 */

public abstract class RBaseAdapter<T> extends RecyclerView.Adapter<RViewHolder> {
    private Context mContext;
    private List<T> list;
    protected LayoutInflater mInflater;
    private int mItemLayoutId;

    /**
     * 以下四个为构造函数，根据需要自行修改
     * @param context
     */
    public RBaseAdapter(Context context) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(mContext);
        this.mItemLayoutId = new LinearLayout(mContext).getId();
        this.list = new ArrayList<T>();
    }

    public RBaseAdapter(Context context, List<T> list) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(mContext);
        this.mItemLayoutId = new LinearLayout(mContext).getId();
        this.list = list;
    }

    public RBaseAdapter(Context context, List<T> list, int itemLayoutId) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(mContext);
        this.mItemLayoutId = itemLayoutId;
        this.list = list;
    }

    public RBaseAdapter(Context context, int itemLayoutId) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(mContext);
        this.mItemLayoutId = itemLayoutId;
        this.list = new ArrayList<T>();
    }

    /**
     *获取上下文
     */
    public Context getmContext(){
        return this.mContext;
    }

    public void setItemLayoutId  (int itemLayoutId){
        this.mItemLayoutId = itemLayoutId;
    }

    public List<T> getList(){
        return this.list;
    }

    /**
     * 适配器数据发生变化变化调用
     * @param list
     */
    public void appendList(List<T> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    /**
     * 追加适配器数据
     * @param list2
     */
    public void addList(List<T> list2) {
        this.list.addAll((Collection<? extends T>) list2);
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return list.size();
    }


    @Override
    public void onBindViewHolder(RViewHolder holder, int position) {
            convert(holder, (T) list.get(position));
    }

    @Override
    public RViewHolder onCreateViewHolder(ViewGroup parent, int position) {
            return RViewHolder.get(mContext, parent, mItemLayoutId, position);
    }

    /**
     * 实例化控件事件
     * 具名函数与匿名函数均可
     * @param holder
     * @param item
     */
    public abstract void convert(RViewHolder holder, T item);
}
